import 'dart:collection';
import 'dart:convert';

import 'package:base/resources/base_constants.dart';
import 'package:base/widgets/error_view.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'option.dart';

///百度echartView 封装
class EchartView extends StatefulWidget {
  final Option option;

  EchartView({required this.option, Key? key}) : super(key: key);

  @override
  _EchartViewState createState() => new _EchartViewState();
}

class _EchartViewState extends State<EchartView> {
  late InAppWebViewController _webViewController;
  InAppWebViewGroupOptions _options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  String? _error;

  String package = BaseConstants.PACKAGE;

  static const String METHOD_INIT = "init";

  static const String METHOD_FINISHED = "isFinished";

  int _index = 0;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: IndexedStack(
        index: _index,
        children: [
          Center(
            child: SizedBox(
              height: 24,
              width: 24,
              child: CircularProgressIndicator(
                strokeWidth: 2,
              ),
            ),
          ),
          InAppWebView(
            initialFile: "packages/$package/assets/web/html/echart.html",
            gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
              Factory<VerticalDragGestureRecognizer>(
                  () => VerticalDragGestureRecognizer()),
              Factory<ScaleGestureRecognizer>(
                () => ScaleGestureRecognizer(),
              ),
              Factory<PanGestureRecognizer>(() => PanGestureRecognizer()),
            ].toSet(),
            initialUserScripts: UnmodifiableListView<UserScript>([]),
            initialOptions: _options,
            onWebViewCreated: (controller) {
              _webViewController = controller;
              _webViewController.addJavaScriptHandler(
                  handlerName: METHOD_INIT,
                  callback: (arg) {
                    if (arg.length > 0) {
                      bool init = arg[0];
                      if (init) {
                        String json = jsonEncode(widget.option);
                        _webViewController.evaluateJavascript(
                            source: "setOption($json)");
                      }
                    }
                  });

              _webViewController.addJavaScriptHandler(
                  handlerName: METHOD_FINISHED,
                  callback: (arg) {
                    if (arg.length > 0) {
                      bool finished = arg[0];
                      if (finished) {
                        setState(() {
                          _index = 1;
                          _error = null;
                        });
                      }
                    }
                  });
            },
            onLoadStart: (controller, url) {},
            androidOnPermissionRequest: (controller, origin, resources) async {
              return PermissionRequestResponse(
                  resources: resources,
                  action: PermissionRequestResponseAction.GRANT);
            },
            onLoadError: (controller, url, code, message) {
              setState(() {
                _index = 2;
                _error = message;
              });
            },
            onConsoleMessage: (controller, consoleMessage) {
              print(consoleMessage);
            },
          ),
          ErrorView(
            error: _error,
          )
        ],
      ),
    );
  }
}
